<template>
  <div id="app" style="overflow: hidden;width:100%;height:100%;">
    <vxe-grid ref="xGrid" v-bind="grid_options">

    </vxe-grid>
    <el-dialog v-dialogDrag top="0px" :title="formModel.title" :visible.sync="formModel.dialogVisible"
               :width="formModel.width" :closeOnClickModal="formModel.closeOnClickModal" :before-close="handleClose">
      <t-bizc-enery-equip-form v-if="formModel.dialogVisible && formModel.componentId == 'TBizcEneryEquipForm'"
                               :formData="formModel.TBizcEneryEquipFormData"
                               @closeEvent="handleClose">
      </t-bizc-enery-equip-form>
      <!-- 其他的弹出组件可以写在这里面 -->
    </el-dialog>
    <approvalLabel ref="approvalLabel" @onSearch="onSearch"></approvalLabel>
  </div>


</template>

<script>
import {reactive} from 'vue'
import {formModel, GridEvent} from './model/approval-table'
import {approvallabel} from '@/api/equip/approvallabel.js'
import {CommonApi} from '@/api/equip/CommonApi.js'
import approvalLabel from './components/approvallabel.vue'
import util from '@/utils/util'
import VXETable from "vxe-table";
import {getInfo} from "@/api/login";
import {listDept} from "@/api/system/dept";

export default {
  name: 'approvallabel',
  components: {
    TBizcEneryEquipForm: () => import("./components/countequipForm.vue"),
    approvalLabel
  },
  data() {
    return {
      GridEvent: reactive(GridEvent),
      formModel: reactive(formModel),
      grid_options: {
        border: true,
        stripe: true,
        showHeaderOverflow: false,
        showOverflow: true,
        keepSource: true,
        id: 'full_edit_1',
        height: 700,
        rowId: 'id',  //指定记录主键
        rowConfig: {
          isHover: true
        },
        columnConfig: {
          resizable: true
        },
        customConfig: {
          storage: true,
          // checkMethod: this.checkColumnMethod
        },
        sortConfig: {
          trigger: 'cell',
          remote: true
        },
        filterConfig: {
          remote: true
        },
        formConfig: {
          form: true, // 启用表单代理
          size: "medium",        //尺寸
          titleAlign: "right",  //所有项的标题对齐方式
          titleWidth: "120", //标题宽度
          titleColon: true,     //是否显示标题冒号
          items: [
            {
              field: 'gldwbm',
              title: '单位:',
              span: 6,
              itemRender: {name: '$select', options: [], props: {placeholder: '---请选择---'}}
            },
            {
              field: 'sbmc',
              title: '设备名称:',
              span: 6,
              itemRender: {name: '$input', props: {placeholder: '请输入设备名称'}}
            },
            {
              field: 'ccbm',
              title: '出厂编码:',
              span: 6,
              itemRender: {name: '$input', props: {placeholder: '请输入出厂编码'}}
            },
            // { field: 'sbgg', title: '规格:', span: 6, itemRender: { name: '$input',props: { placeholder: '请输入规格' } }},
            {
              field: 'sblxbm',
              title: '设备类型:',
              span: 6,
              itemRender: {name: '$select', options: [], props: {placeholder: '---请选择---',}},
              folding: true
            },
            {
              field: 'yxzt',
              title: '运行状态:',
              span: 6,
              itemRender: {name: '$select', options: [], props: {placeholder: '---请选择---',}},
              folding: true
            },
            {
              field: 'shztbm',
              title: '审核状态',
              span: 6,
              itemRender: {name: '$select', options: [], props: {placeholder: '---请选择---'}},
              folding: true
            },
            // { field: 'tqTime', title: '贴签时间', span: 6, itemRender: { name: '$input', props: { type: 'datetime',placeholder: '请选择贴签时间' }},folding: true},
            // { field: 'tqTime_to', title: '至', span: 6, itemRender: { name: '$input', props: { type: 'datetime',placeholder: '请选择贴签时间' }},folding: true},
            {
              field: 'sftq',
              title: '是否贴签',
              span: 6,
              itemRender: {
                name: '$select',
                options: [{label: '否', value: '0'}, {label: '是', value: '1'},],
                props: {placeholder: '---请选择---'}
              },
              folding: true
            },

            {
              span: 6, collapseNode: true, align: 'right', itemRender: {
                name: '$buttons', children: [
                  {props: {type: 'submit', content: '查询', status: 'primary', icon: 'fa fa-search'}},
                  {props: {type: 'reset', content: '重置', icon: 'fa fa-reply'}},
                ]
              }
            }
          ]
        },
        toolbarConfig: {
          // buttons: [
          //   { buttonRender: { name: 'export', events: { click: this.exportModal } } }, // 导出
          // ],
          refresh: true,
          custom: true,
          export: {
            icon: 'fa fa-arrow-down',

          },
        },
        exportConfig: {
          remote: true,
          exportMethod: this.exportModal,
          // types: ['xlsx', 'xls'],
          // modes: ['current', 'selected', 'all']
        },
        pagerConfig: {
          pageSize: 10,
          pageSizes: [5, 10, 15, 20, 50, 100],
          layouts: ['PrevJump', 'PrevPage', 'JumpNumber', 'NextPage', 'NextJump', 'Sizes', 'FullJump', 'Total'],
          background: true,
          fixed: true,
        },
        proxyConfig: {
          seq: true, // 启用动态序号代理，每一页的序号会根据当前页数变化
          sort: true, // 启用排序代理，当点击排序时会自动触发 query 行为
          filter: true, // 启用筛选代理，当点击筛选时会自动触发 query 行为
          form: true, // 启用表单代理，当点击表单提交按钮时会自动触发 reload 行为
          // 对应响应结果 { result: [], page: { total: 100 } }
          props: {
            result: 'data.records', // 配置响应结果列表字段
            total: 'data.total' // 配置响应结果总页数字段
          },
          // 只接收Promise，具体实现自由发挥
          ajax: {
            // 当点击工具栏查询按钮或者手动提交指令 query或reload 时会被触发
            query: ({page, sorts, filters, form}) => {
              // =====给表单项赋初始值======
              //  this.initFormData(form);
              //    this.enableDefault = false;
              if (form.sftq === undefined || form.sftq === null) {
                form.sftq = '1'
              }

              const queryParams = Object.assign({}, form)
              // const queryParams = this.initFormData(form)
              // 处理排序条件
              const firstSort = sorts[0]
              if (firstSort) {
                queryParams.sort = firstSort.property
                queryParams.order = firstSort.order
              }
              // 处理筛选条件

              filters.forEach(({property, values}) => {
                queryParams[property] = values.join(',')
              })
              return this.queryData(page, queryParams)
            },
          }
        },
        columns: [
          {type: 'seq', title: '序号', width: 60, align: 'center', headerAlign: 'center'},
          {
            field: 'caozuo',
            title: '操作',
            minWidth: "100px",
            align: 'center',
            headerAlign: 'center',
            visible: true,
            cellRender: {name: 'sh', events: {click: this.shRowModal}}
          },

          {field: 'gldwmc', title: '单位', minWidth: "160px", align: 'center', headerAlign: 'center',},
          {field: 'sbmc', title: '设备名称', minWidth: "160px", align: 'center', headerAlign: 'center',},
          {
            field: 'ccbm',
            title: '出厂编码',
            minWidth: "160px",
            align: 'center',
            headerAlign: 'center',
            cellRender: {name: 'ccbm', events: {click: this.handleccbm}}
          },
          {field: 'sblxmc', title: '设备类型', minWidth: "100px", align: 'center', headerAlign: 'center',},
          {field: 'pt', title: 'PT', minWidth: "100px", align: 'center', headerAlign: 'center',},
          {field: 'ct', title: 'CT', minWidth: "100px", align: 'center', headerAlign: 'center',},
          {field: 'sbztmc', title: '设备状态', minWidth: "160px", align: 'center', headerAlign: 'center',},
          {field: 'shztmc', title: '审核状态', minWidth: "100px", align: 'center', headerAlign: 'center',},
          {field: 'yxztmc', title: '运行状态', minWidth: "100px", align: 'center', headerAlign: 'center',},
          {field: 'sbgg', title: '规格', minWidth: "100px", align: 'center', headerAlign: 'center',},
          {field: 'xh', title: '型号', minWidth: "100px", align: 'center', headerAlign: 'center',},
          {field: 'sskfmc', title: '所属库房', minWidth: "100px", align: 'center', headerAlign: 'center',},
          // { field: 'sftq', title: '是否贴签', minWidth: "100px", align: 'center', headerAlign: 'center', },

          // { field: 'tqTime', title: '贴签时间', minWidth: "160px", align: 'center', headerAlign: 'center', },
          // { field: 'ewmzp', title: '二维码', minWidth: "150px", align: 'center', headerAlign: 'center',cellRender: { name: 'erweima'} },
          // { field: 'qjzp', title: '设备照片', minWidth: "150px", align: 'center', headerAlign: 'center', cellRender: { name: 'qjzp'}},
          // { field: 'shyj', title: '审核意见', minWidth: "160px", align: 'center', headerAlign: 'center',showOverflow:true },
        ],
        checkboxConfig: {
          // labelField: 'id',
          reserve: true,
          highlight: true,
          range: true
        },
        editConfig: {
          trigger: 'click',
          mode: 'row',
          showStatus: true
        }
      },
      //  api: 'fetchQueryQueryRwxqByPage',
      // init: true
    }
  },
  created() {
    this.setReadModel()
  },
  mounted() {
    this.$nextTick(function () {
      this.sblxbm_Option()
      this.shztbm_Option()
      this.dw_Option()
      this.yxzt_Option()
    })
    window.addEventListener('resize', this.setTableHeight);
  },
  destroyed: function () {
    window.removeEventListener('resize', this.setTableHeight);
  },
  methods: {
    handleClose(e) {
      formModel.closeDialogEvent(e, this.$refs.xGrid)
    },
    // 高度自适应
    setTableHeight: function () {
      const tableContainer = document.querySelector("#app");
      const height = tableContainer.clientHeight;
      this.grid_options.height = height - 5;
    },
    handleccbm(val) {
      GridEvent.editForm(val);
    },
    //查询控制
    setReadModel() { //控制是否显示
      const isRead = util.isReadModel()
      if (isRead) {
        this.grid_options.columns[1].visible = false
        this.grid_options.formConfig.items[5].visible = false
      } else {
        // this.grid_options.columns[2].visible=false
      }
    },
    dw_Option() {
      getInfo().then(res => {
        let params = {
          deptId: res.user.dept.deptId,
          parentId: res.user.dept.parentId
        }
        listDept(params).then(result => {
          let optionList = [
            {label: '请选择', value: ''}
          ]
          result.data.forEach((item) => {
            optionList.push({label: item.deptName, value: item.deptId})

          })
          const item = this.$refs.xGrid.getFormItems(0)
          item.itemRender.options = optionList

        })

      })
    },
    yxzt_Option() {
      CommonApi.queryDictData('EN_EQUIP_YXZT').then(res => {

          // 修改编辑框
          // const sexColumn = $grid.getColumnByField('sex')
          // sexColumn.editRender.options = sexList
          // 修改查询条件列表
          let optionList = [
            {label: '请选择', value: ''}
          ]
          res.data.forEach((item) => {
            // console.log(item,'item.,,,');
            optionList.push({label: item.value, value: item.code})
          })

          const item = this.$refs.xGrid.getFormItems(4)
          item.itemRender.options = optionList

        }
      ).catch(err => {
        console.log(err)
      })
    },
    sblxbm_Option() {
      approvallabel.queryDictData('1000').then(res => {
        let optionList = [
          {label: '请选择', value: ''}
        ]
        res.data.forEach((item) => {
          optionList.push({label: item.name, value: item.id})
        })
        const item = this.$refs.xGrid.getFormItems(3)
        item.itemRender.options = optionList

      }).catch(err => {
        console.log(err)
      })
    },
    shztbm_Option() {
      approvallabel.queryLeaf('EN_EQUIP_BQ_STATE').then(res => {
        let optionList = [
          {label: '请选择', value: ''}
        ]
        res.data.forEach((item) => {
          optionList.push({label: item.value, value: item.code})
        })
        const item = this.$refs.xGrid.getFormItems(5)
        item.itemRender.options = optionList

      }).catch(err => {
        console.log(err)
      })

    },
    onSearch() {
      this.$refs.xGrid.commitProxy('query')
    },
    rowClassName(val) {
      if (val.row.sftq === '是' && val.row.shztbm === '30') {
        return 'row-red'
      } else {
        return 'row-info'
      }
    },
    // initFormData(form) {
    //    form = this.headerData
    //    return form
    // },
    queryData: (page, formData) => {
      const queryParam = Object.assign({}, formData)
      const queryParams = {
        entity: queryParam,
        column: "",
        order: "",
        pageSize: page.pageSize,
        pageNo: page.currentPage,
        paramsMap: {}
      }
      return approvallabel.getdata(queryParams)
    },
    shRowModal(row) {
      this.$refs.approvalLabel.showDialog(row)
    },

    handleDelete() {
      alert('取消工单')
    },
    //导出
    exportModal() {
      // const dataParams={}
      const queryParam = Object.assign({}, this.$refs.xGrid.getProxyInfo().form)
      const queryParams = {
        entity: queryParam,
        column: "",
        order: "",
        pageSize: this.$refs.xGrid._data.tablePage.pageSize,
        pageNo: this.$refs.xGrid._data.tablePage.currentPage,
        paramsMap: {}
      }
      approvallabel.exportXls(queryParams).then(res => {
        util.download(res, '设备标签审核' + (moment().format("YYYY-MM-DD")) + '.xls')
      }).catch(err => {
        console.log(err)
      })
    }
  }
}
// 创建一个简单的工具栏-左侧按钮渲染
VXETable.renderer.add('add', {
  renderToolbarButton(h, renderOpts, params) {
    const {events = {}} = renderOpts
    const {button, $table} = params
    return [
      <vxe-button icon="fa fa-plus (alias)" content="审核" onClick={
        () => {
          events.click(button)
        }
      }></vxe-button>
    ]
  }
})
// 创建一个简单的工具栏-左侧按钮渲染
VXETable.renderer.add('export', {
  renderToolbarButton(h, renderOpts, params) {
    const {events = {}} = renderOpts
    const {button, $table} = params
    return [
      <vxe-button icon="fa fa-arrow-down" content="导出" onClick={
        () => {
          events.click(button)
        }
      }></vxe-button>
    ]
  }
})

VXETable.renderer.add('sh', {
  // 默认显示模板
  renderDefault(h, renderOpts, params) {
    let {row, column} = params
    let {events} = renderOpts
    return [
      <el-button type={row.shztbm === '10' ? 'primary' : 'info'} disabled={row.shztbm === '10' ? false : true}
                 size="small" onClick={() => events.click(row)} size="small">审核</el-button>
    ]
  },
})
VXETable.renderer.add('erweima', {
  // 默认显示模板
  renderDefault(h, renderOpts, params) {
    let {row, column} = params
    let {events} = renderOpts
    let url = row.ewmzp ? row.ewmzp.split(',')[0] : ""
    let erweimaList = row.ewmzp && row.ewmzp.split(',')
    let urlList = []
    if (erweimaList !== null) {
      erweimaList.forEach(item => {
        if (item == null) {
        } else {
          urlList.push(item)
        }

      })

    }
    return [
      <el-image src={url} preview-src-list={urlList}></el-image>
    ]

  },
})
VXETable.renderer.add('qjzp', {
  // 默认显示模板
  renderDefault(h, renderOpts, params) {
    let {row, column} = params
    let {events} = renderOpts
    let url = row.qjzp
    let urlList = [row.qjzp]
    return [
      <el-image src={url} preview-src-list={urlList}></el-image>
    ]
  },
})
// 出场编号穿透渲染
VXETable.renderer.add('ccbm', {
  renderDefault(h, renderOpts, params) {
    const {events = {}} = renderOpts
    const {row, column} = params
    return [
      <span style="color:#0000FF;cursor: pointer;" onClick={
        () => {
          events.click(params.row)
        }
      }>{params.row.ccbm}</span>
    ]
  }
})
</script>

<style scoped>
.mytable-style .vxe-body--row.row-red {
  background-color: #187;
  color: red !important;
}
</style>
